var aes = require('../common/aes-cbc.js');
/**
 * 生成随机数
 */
function RndNum(n) {
  var rnd = "";
  for (var i = 0; i < n; i++)
    rnd += Math.floor(Math.random() * 10);
  return rnd;
};

//去除重复元素
function uniqueArr(arr) {
  var result = [];
  for (var i = 0; i < arr.length; i++) {
    if (result.indexOf(arr[i]) == -1) {
      result.push(arr[i])
    }
  }
  return result;
}
function checkinput(s) {
  var regu = /^[0-9]*$/;
  var re = new RegExp(regu);
  if (re.test(s)) {
    return true;
  } else {
    return false;
  }
}

function checkdata(s) {
  var regu = /^[0-9]+(.[0-9]+)?$/;
  var re = new RegExp(regu);
  if (re.test(s)) {
    return true;
  } else {
    return false;
  }
}
/**
 * 验证汉字
 */
function checkword(s) {
  var regu = /^[\u4e00-\u9fa5]+$/;
  var re = new RegExp(regu);
  if (re.test(s)) {
    return true;
  } else {
    return false;
  }
}
/**
 *验证姓名
 */
function checkname(s) {
  var regu = /^[\u4e00-\u9fa5]+$/;
  var re = new RegExp(regu);
  if (re.test(s)) {
    return true;
  } else {
    return false;
  }
}
/**
 * 检测身份证号码
 */
function checkidcard(s) {
  var regu = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/;
  var re = new RegExp(regu);
  if (re.test(s)) {
    return true;
  } else {
    return false;
  }
}

/**
 * 生成签名
 */
function SetSign(array) {
  var arr = array.sort();
  var str = arr[0] + arr[1] + arr[2] + arr[3];
  return aes.AES_Encrypt(str);
}

/**
 * 转义
 */
function toUnicode(arg) {
  var result = '';
  var character;
  for (var i = 0; i < arg.length; i++) {
    character = arg.charCodeAt(i).toString(16);
    switch (character.length) {
      case 1:
        character = '000' + character
        break;
      case 2:
        character = '00' + character
        break;
      case 3:
        character = '0' + character
        break;
    }
    result += '\\u' + character;
  }
  return result;
}

/**
 * 网络请求
 */
function api(url, method, params, callback) {
  var nonce = this.RndNum(32);
  var timeStamp = Date.parse(new Date()) / 1000;
  var token = wx.getStorageSync('token')
  wx.request({
    url: getApp().data.url + url,
    data: {
      "params": aes.AES_Encrypt(JSON.stringify(params)),
      'nonce': nonce,
      'timestamp': timeStamp,
      'authInfo': token,
      'signature': SetSign([aes.AES_Encrypt(JSON.stringify(params)), nonce, timeStamp, token]),
    },
    method: method,
    header: {
      'content-Type': 'application/json'
    },
    success: function(res) {
      var data = aes.AES_Decrypt(res.data.data);
      var info = JSON.parse(data);
      callback(info)
    },
    fail: function(res) {
      wx.showToast({
        title: '请检查网络',
        icon: 'none'
      })
    }
  })
}

/**
 * 检测用户权限(手机号)
 */
function checkauth(app) {
  if (app.data.userinfo == undefined) {
    wx.showLoading({
      title: '请检查网络后重试',
    })
    return 0;
  }
  if (app.data.userinfo.mobile == '') {
    wx.showModal({
      title: '未绑定手机号',
      content: '现在去绑定吗？',
      success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/user/authlist',
          })
        }
      }
    })
    return 0;
  }
  return 1;
}
/**
 * 用户vip权限检测
 */
function checkvip(user) {
  if (user.user_type !== 2) {
    wx.showModal({
      title: '温馨提示',
      content: '会员专属功能，请先充值成为会员',
      success: function(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/user/vip/vip/vip_center',
          })
        }
      }
    })
    return 0;
  }
  if (user.user_type == 2 && user.vip_time < Date.parse(new Date())) {
    wx.showModal({
      title: '开通会员',
      content: '现在开通吗？',
      success: function(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/user/vip/vip/vip_center',
          })
        }
      }
    })
    return 0;
  }
  return 1;
}

//用户登录
function login(callback) {
  var that = this;
  wx.login({
    success: function(res) {
      if (res.code) {
        //发起网络请求 
        var params = {
          "code": res.code
        }
        that.api('login/login', 'POST', params, function(data) {
          callback(data);
        })
      } else {
        console.log('登录失败！' + res.errMsg)
      }
    },
    fail: function(e) {
      console.log(e)
    }
  });
}

function checkIdentify(user) {
  if (user.user_status !== 1) {
    wx.showModal({
      title: '未实名',
      content: '请先进行实名认证',
      success: function(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/user/personal_authentication/personal_authentication',
          })
        }
      }
    })
    return 0;
  } else {
    return 1;
  }
}
/**
 * 用户上传图片
 */
function UploadImage(url, app, SuccessCallBack, FailCallBack) {
  var params = {
    "app": app
  }
  var nonce = RndNum(32);
  var timeStamp = Date.parse(new Date());
  var token = wx.getStorageSync('token');
  wx.chooseImage({
    sizeType: ['original'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      count: 1,
    success: function(res) {
      var tempFilePaths = res.tempFilePaths
      wx.uploadFile({
        url: getApp().data.url + url,
        filePath: tempFilePaths[0],
        name: 'file',
        formData: {
          "params": aes.AES_Encrypt(JSON.stringify(params)),
          'nonce': nonce,
          'timestamp': timeStamp,
          'authInfo': token,
          'signature': SetSign([aes.AES_Encrypt(JSON.stringify(params)), nonce, timeStamp, token])
        },
        success: function(res) {
          var data = JSON.parse(res.data);
          var jsonStr = aes.AES_Decrypt(data.data);
          jsonStr = jsonStr.replace(" ", "");
          if (typeof jsonStr != 'object') {
            jsonStr = jsonStr.replace(/\ufeff/g, ""); //重点
            var jj = JSON.parse(jsonStr);
            res.data = jj;
          }
          if (res.data.success == 1) {
            SuccessCallBack(res.data);
          } else {
            console.log('fail');
            console.log(res.data);
            return;
            FailCallBack(res.data);
     
          }
        }
      })
    }
  })
}
//更改公司信息
function set_company_info() {
  var that = this;
  var params = {
    "type": "get_company_info"
  };
  that.api('userinfo/get_company', 'GET', params, function(data) {
    if (data.success == 1) {
      getApp().data.userinfo.company_info = data.data;
    }
  })
}

// 统一搜集用户FormID，用于推送消息
function CollectFormId(formId, userID, callback) {
  var that = this;
  var params = {
    'formId': formId,
    'userID': userID
  };
  that.api('send_message/CollectFormId', 'POST', params, function(data) {
    callback(data);
  })
}

module.exports = {
  RndNum: RndNum,
  checkinput: checkinput,
  checkdata: checkdata,
  checkword: checkword,
  checkname: checkname,
  checkidcard: checkidcard,
  api: api,
  checkauth: checkauth,
  checkvip: checkvip,
  login: login,
  set_company_info: set_company_info,
  SetSign: SetSign,
  UploadImage: UploadImage,
  CollectFormId: CollectFormId,
  checkIdentify: checkIdentify,
  uniqueArr: uniqueArr
}